<template>
  <div>
    <top-bar></top-bar>
    <left-bar :datas='data'></left-bar>
    <div class="adddrug system">
      <home-bar :currentPage='currentPage'></home-bar>
      <div class="adddrugs system-main">
        <div class="main-position">
          首页 > 药品管理 > 进货管理
        </div>
        <div class="main-height"></div>
        <div class="main-mains">
          <div class="main-top-nav">
            <ul>
              <router-link to="/stockmanagement" @click.native="addPath('/stockmanagement','药品管理');">
                <li class="active">进货管理</li>
              </router-link>
              <router-link to="/druglistai/xiajia" @click.native="addPath('/druglistai/xiajia','药品管理');">
                <li>已下架</li>
                <router-link to="/druglistai/deleteddrugs" @click.native="addPath('/druglistai/deleteddrugs','药品管理');">
                  <li>已删除药品</li>
                </router-link>
              </router-link>
              <router-link to="/druglistai/shortageofdrugs" @click.native="addPath('/druglistai/shortageofdrugs','药品管理');">
                <li>缺货药品</li>
              </router-link>
              <router-link to="/willexpire" @click.native="addPath('/willexpire','药品管理');">
                <li>即将过期</li>
              </router-link>
              <router-link to="/expired" @click.native="addPath('/expired','药品管理');">
                <li>已过期</li>
              </router-link>
              <router-link to="/druglistai/lackdrug" @click.native="addPath('/druglistai/lackdrug','药品管理');">
                <li>库存预警</li>
              </router-link>
              <router-link to="/productcategorymgmt" @click.native="addPath('/productcategorymgmt','药品管理');">
                <li>产品种类管理</li>
              </router-link>
              <router-link to="/brandlibrary" @click.native="addPath('/brandlibrary','药品管理');">
                <li>品牌库</li>
              </router-link>
            </ul>
          </div>
          <!-- 加载gif图 -->
          <div class="loadingGif" v-if="showLoadingGif"><img src="../../images/loading.gif" alt=""></div>
          <!-- 加载gif图 -->
          <div class="drugListMain" v-if="!showLoadingGif">
            <div class="moreScreeningKeyword" v-show="moreScreeningKeyword">
              <li v-for="(screening,index) in moreScreeningKeywordList" :key="index">
                <span>{{screening.key}}：</span>
                <span>{{screening.value}}</span>
                <i class="el-icon-close" @click="deleteScreeningKeywordItem(index)"></i>
              </li>
            </div>
            <div class="headOperation">
              <a href="javascript:void(0);" class="OperationA" @click="clickAddStock">新增进货</a>
              <!-- <a href="javascript:void(0);" class="OperationA" @click="clickPatchExport">批量导出</a> -->
              <a href="javascript:void(0);" class="OperationA" @click="clickScreeningPopup">筛选</a>
              <div class="drugListSearch">
                <el-input placeholder="请输入内容" suffix-icon="el-icon-search" v-model="input21">
                </el-input>
              </div>
              <a href="javascript:void(0);" class="OperationA-color" @click="clearScreeningConditions">清空筛选条件</a>
              <i class="iconDown iconfont icon-xiala" @click="moreScreeningKeyword = moreScreeningKeyword == false ? true : false" v-if="iconDownSwitch"></i>
              <div class="screeningKeyword">
                <span v-for="(screening,index) in moreScreeningKeywordList" :key="index">
                                          {{screening.value.length > 6 ? screening.value.slice(0,6) + '...' : screening.value}}
                                          <i class="el-icon-close" @click="deleteScreeningKeywordItem(index)"></i>
                                        </span>
              </div>
            </div>
            <!--/.headOperation -->
            <div class="drugListTable">
              <table>
                <tr>
                  <td>生产批号</td>
                  <td>图片</td>
                  <td>药品分类</td>
                  <td>药品编码</td>
                  <td>药品名称</td>
                  <td>品牌</td>
                  <td>处方/非处方</td>
                  <td>经营范围</td>
                  <td>批发价</td>
                  <td>库存</td>
                  <td>生产日期</td>
                  <td>保质期</td>
                  <td>进货日期</td>
                  <td>信息费比例</td>
                  <td>药品状态</td>
                  <td>推荐药品</td>
                  <td>操作</td>
                </tr>
                <tr v-for="(trading,index) in tableList" :key="index">
                  <td>{{trading.batch_num}}</td>
                  <td>
                    <img :src="trading.image_url" alt="" class="trImg">
                  </td>
                  <td width="150px">{{trading.category_name}}</td>
                  <td><router-link :to="{name:'agentadddrug',params:{coding:trading.coding}}">{{trading.coding}}</router-link></td>
                  <td>{{trading.name}}</td>
                  <td>{{trading.brand_name}}</td>
                  <td>{{trading.med_type | medType }}</td>
                  <td width="150px">{{trading.scope_name}}</td>
                  <td>
                    <el-tooltip placement="top">
                      <div slot="content">{{trading.pur_price}}</div>
                      <el-button style="width:150px;">{{trading.pur_price}}</el-button>
                    </el-tooltip>
                  </td>
                  <td>{{trading.stock}}</td>
                  <td>{{trading.manu_date}}</td>
                  <td>{{trading.shelf_life}}</td>
                  <td>{{trading.pur_time}}</td>
                  <td>{{trading.info_fee_rate * 100 + '%'}}</td>
                  <td>{{trading.status==1?"已上架":""}}</td>
                  <td>{{trading.is_recommend == 0 ? "否" : "是"}}</td>
                  <td>
                    <el-tooltip placement="left">
                      <div slot="content">编辑</div>
                      <el-button><i class="iconfont icon-bianji" @click="editFun(trading.id)"></i></el-button>
                    </el-tooltip>
                    <el-tooltip placement="left" v-if="trading.status == 1">
                      <div slot="content">下架{{trading.id}}</div>
                      <el-button><i class="iconfont icon-xiajia" @click="clickChangeStatus(trading.id,trading.coding,trading.name,trading.brand_name,trading.info_fee_rate,trading.stock,trading.manu_date,trading.shelf_life)"></i></el-button>
                    </el-tooltip>
                    <el-tooltip placement="left">
                      <div slot="content" v-if="trading.is_recommend == 0">设为推荐药品</div>
                      <div slot="content" v-else-if="trading.is_recommend == 1">取消推荐药品</div>
                      <el-button><i class="iconfont icon-tuijian" :class="{green:trading.is_recommend == 1}" @click="is_recommendFun(trading.is_recommend,trading.id,index)"></i></el-button>
                    </el-tooltip>
                  </td>
                </tr>
              </table>
            </div>
            <div class="pageBotom">
              <div class="pageBotomRight">
                    <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage4"
              :page-size="20"
              layout="total, prev, pager, next"
              :total="totalNumOfArticle">
            </el-pagination>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 弹窗开始 -->
      <div class="system-menban" v-show="showSystemPopup"></div>
      <div class="systemPopup" v-show="showSystemPopup">
        <div class="topTitle">
          <span>{{systemPopupTitle}}</span>
          <i class="el-icon-close system-icon" @click="hideSystemPopup"></i>
        </div>
        <!-- 筛选弹窗 -->
        <div class="screeningPopup clear" v-show="showScreeningPopup">
          <ul class="clear">
            <li>
              <span class="spanTitle">修改日期</span>
              <div class="inputBox">
                <el-date-picker v-model="screeningValueList.changeDateValue" type="date" placeholder="修改日期">
                </el-date-picker>
              </div>
            </li>
            <li>
              <span class="spanTitle">药品类型</span>
              <div class="inputBox">
                <el-select v-model="screeningValueList.drugTypeValue">
                  <el-option v-for="item in screeningValueList.drugTypeOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </li>
            <li>
              <span class="spanTitle">药监类目</span>
              <div class="inputBox">
                <el-select v-model="screeningValueList.drugCategoryValue">
                  <el-option v-for="item in screeningValueList.drugCategoryOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </li>
            <li>
              <span class="spanTitle">库存范围</span>
              <div class="inputBox doubleInputBox">
                <el-input placeholder="请输入内容"></el-input>
                <span class="horizontalLine"></span>
                <el-input placeholder="请输入内容"></el-input>
              </div>
            </li>
            <li>
              <span class="spanTitle">信息费比例</span>
              <div class="inputBox doubleInputBox">
                <el-select v-model="bakValue" placeholder="请选择">
                  <el-option v-for="item in bakoption" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
                <span class="horizontalLine"></span>
                <el-select v-model="bakValue" placeholder="请选择">
                  <el-option v-for="item in bakoption" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </li>
            <li>
              <span class="spanTitle">关键字搜索</span>
              <div class="inputBox">
                <input type="text" class="orgInput">
              </div>
            </li>
          </ul>
          <div class="system-messagebox1-btn clear">
            <div>确定</div>
            <div @click="hideSystemPopup">取消</div>
          </div>
        </div>
        <!--/.screeningPopup -->
        <!-- 批量导出 -->
        <div class="patchExportPopup" v-show="showPatchExport">
          <div class="topText">请编辑您需要的数据<span>编辑后您导出的Excel表格会显示以下数据</span></div>
          <div class="patchExportCheckbox">
            <el-checkbox-group v-model="businessType">
              <el-checkbox label="中成药"></el-checkbox>
              <el-checkbox label="生化药品"></el-checkbox>
              <el-checkbox label="一类医疗器械"></el-checkbox>
              <el-checkbox label="体外诊断试剂"></el-checkbox>
              <el-checkbox label="中药饮片"></el-checkbox>
              <el-checkbox label="疫苗"></el-checkbox>
              <el-checkbox label="无证的二类医疗器械"></el-checkbox>
              <el-checkbox label="其它药品"></el-checkbox>
              <el-checkbox label="保健药品"></el-checkbox>
              <el-checkbox label="抗生素"></el-checkbox>
              <el-checkbox label="化学药制剂"></el-checkbox>
              <el-checkbox label="二类精神药品"></el-checkbox>
              <el-checkbox label="三类医疗器械"></el-checkbox>
              <el-checkbox label="其它药品"></el-checkbox>
            </el-checkbox-group>
          </div>
          <div class="bottomText">导出格式Excel表格（.xls文件）</div>
          <div class="system-messagebox1-btn clear">
            <div @click="determineTheExport">确定导出</div>
            <div @click="hideSystemPopup">取消</div>
          </div>
        </div>
        <!--/.patchExportPopup -->
        <!-- 批量导出成功 -->
        <div class="okPopup" v-show="showExportOkPopup">
          <i class="iconfont icon-web-icon-"></i>
          <h3>导出成功</h3>
          <div class="system-messagebox1-btn clear">
            <div @click="hideSystemPopup">确定</div>
          </div>
        </div>
        <!-- 新增进货、编辑库存 -->
        <div class="addStockPopup" v-if="showAddStockPopup">
          <div class="seeCoding" v-if="!isEdit">
            <span class="leftTitle">药品编码</span>
            <el-input placeholder="请输入药品编码或使用扫码枪扫码" v-model="codingValue"></el-input>
            <button @click="clickCodingResults">查询结果</button>
          </div>
          <div class="codingProductDetail" v-if="showCodingProductDetailPopup">
            <div class="productMsg">
              <img :src="medical.image_url" alt="" class="p-img">
              <div class="p-msg">
                <li><span>药品名称</span>{{medical.name}}</li>
                <li><span>药品分类</span>{{medical.category_name}}</li>
                <li><span>生产厂家</span>{{medical.manu_fac}}</li>
                <li><span>批准文号</span>{{medical.lic_num}}</li>
                <li><span>药品条形码</span>{{medical.coding}}</li>
              </div>
            </div>
            <div class="salesRange clear">
              <span class="leftTitle">销售范围</span>
              <div class="rightContent">
                <div class="existingSalesRange">
                  <div class="group" v-for="(item,index) in medical.region_list" :key="index">
                    <div>{{item.province}}
                      <span v-if="item.city_list">
                                  （
                                <span v-for="(sonitem,index) in item.city_list" :key="index">{{sonitem.city}} <em v-if="item.city_list.length - index > 1">、</em></span> )
                      </span>
                    </div>
                    <a href="javascript:void(0);" @click="mgmtTheProvince(item.province_id,index,item.province)">管理该省</a>
                    <a href="javascript:void(0);" v-if="item.city_list" @click="deleteProvince(index)">删除该省</a>
                    <a href="javascript:void(0);" v-else-if="!item.city_list" @click="deleteProvince(index)">删除该地区</a>
                  </div>
                </div>
                <a href="javascript:void(0);" class="addSalesRange" @click="addProvince" v-if="!isQuanGuo">添加销售范围</a>
              </div>
            </div>
            <div class="attrInput clear">
              <li v-if="!isEdit"><span class="leftTitle">进货数量</span>
                <el-input v-model="medical.stock"></el-input>
              </li>
              <li v-if="!isEdit"><span class="leftTitle">生产日期</span>
                <el-date-picker v-model="medical.manu_date" type="date" value-format="yyyy-MM-dd" placeholder="选择日期">
                </el-date-picker>
              </li>
              <li v-if="!isEdit"><span class="leftTitle">保质期</span>
                <el-select v-model="medical.shelf_life" placeholder="请选择">
                  <el-option v-for="item in shelfLifeOptions" :key="item.value" :value="item.value">
                  </el-option>
                </el-select>
              </li>
              <li v-if="!isEdit"><span class="leftTitle">生产批号</span>
                <el-input v-model="medical.batch_num"></el-input>
              </li>
              <li><span class="leftTitle">信息费比例</span>
                <el-select v-model="org_info_fee_rate" placeholder="请选择">
                  <el-option v-for="(item,index) in 48" :key="index" :value="item+'%'">
                  </el-option>
                </el-select>
              </li>
              <li v-if="isEdit"><span class="leftTitle">库存</span>
                <el-input v-model="medical.stock"></el-input>
              </li>
            </div>
            <div class="priceInput">
              <div class="priceBox">
                <span class="leftTitle">定价</span>
                <li v-for="(oprice,index) in org_pur_price_list" :key="index">
                  <el-input placeholder="件" v-model="oprice.min_num"></el-input>
                  <em class="intervalLine">—</em>
                  <el-input placeholder="件" v-model="oprice.max_num"></el-input>
                  <span class="leftTitle priceTitle">售价</span>
                  <el-input placeholder="元" v-model="oprice.price"></el-input>
                  <span class="deletePrice" @click="deletePrice(index)">删除</span>
                </li>
                <div class="addPrice" @click="clickAddPrice">添加定价范围</div>
              </div>
              <div class="system-messagebox1-btn clear">
                <div @click="saveProduct">确定</div>
                <div @click="hideSystemPopup">取消</div>
              </div>
            </div>
          </div>
        </div>
        <!-- 管理该省 -->
        <div class="mgmtTheProvince" v-if="showMgmtTheProvincePopup">
          <div v-if="isMgmtProvince" class="provinceName">{{checkProvince_name}}</div>
          <div class="chooseProvince" v-else-if="!isMgmtProvince">
            <span class="leftTitle">选择省份</span>
            <el-select v-model="provinceValue" placeholder="请选择" @change="provinceValueChange(provinceValue)">
              <el-option v-for="item in province_list_option" :key="item.province_id" :label="item.province" :value="item.province_id">
              </el-option>
            </el-select>
          </div>
          <div class="cityBox">
            <el-checkbox-group v-model="checkedCitys">
              <el-checkbox v-for="(city,index) in city_list_option" :label="city.city_id" :key="city.index" @change="selectCity(index,city.city_id,city.city,city.province_id)">{{city.city}}</el-checkbox>
            </el-checkbox-group>
          </div>
          <div class="system-messagebox1-btn clear">
            <div @click="closeChooseProvince">确定</div>
            <div v-if="!isMgmtProvince" @click="cancelChooseProvince">取消</div>
          </div>
        </div>
        <!-- 下架 -->
        <div class="xiajiaPopup" v-show="showShangXiajiaPopup">
          <div>是否确定下架以下药品？</div>
          <table>
            <tbody>
              <tr>
                <td>
                  药品编号
                </td>
                <td>{{shang_xiajiaValue.coding}}</td>
                <td>
                  药品名称
                </td>
                <td>{{shang_xiajiaValue.name}}</td>
              </tr>
              <tr>
                <td>
                  药品品牌
                </td>
                <td>{{shang_xiajiaValue.brand_name}}</td>
                <td>
                  信息费比例
                </td>
                <td>{{shang_xiajiaValue.info_fee_rate}}</td>
              </tr>
              <tr>
                <td>
                  当前库存
                </td>
                <td>{{shang_xiajiaValue.stock}}</td>
                <td>
                  生产日期
                </td>
                <td>{{shang_xiajiaValue.manu_date}}</td>
              </tr>
              <tr>
                <td>
                  保质期
                </td>
                <td>{{shang_xiajiaValue.shelf_life}}</td>
              </tr>
            </tbody>
          </table>
          <div class="system-messagebox1-btn clear">
            <div @click="changeStatus(2)">确定</div>
            <div @click="hideSystemPopup">取消</div>
          </div>
        </div>
      </div>
      <!-- 弹窗结束 -->
    </div>
  </div>
</template>

<script>
  import topBar from "../../public/top";
  import leftBar from "../../public/left";
  import homeBar from "../../public/homebar";
  export default {
    components: {
      leftBar,
      topBar,
      homeBar
    },
    data() {
      return {
        data: "drugManagment",
        currentPage: {
          path: "/stockmanagement",
          name: "药品管理"
        },
        input21: "",
        //筛选内容
        screeningValueList: {
          changeDateValue: "", //修改日期
          upDateValue: "", //上架日期
          downDateValue: "", //下架日期
          drugTypeValue: "", //药品类型
          stateDrugValue: "", //药品状态
          // informationRateValue: "", //信息费比例
          drugCategoryValue: "", //药品类目
          drugTypeOptions: [
            //药品类型
            {
              value: "选项1",
              label: "黄金糕"
            },
            {
              value: "选项2",
              label: "双皮奶"
            }
          ],
          stateDrugOptions: [
            //药品状态
            {
              value: "选项1",
              label: "黄金糕"
            },
            {
              value: "选项2",
              label: "双皮奶"
            }
          ],
          drugCategoryOptions: [
            //药品类目
            {
              value: "选项1",
              label: "黄金糕"
            },
            {
              value: "选项2",
              label: "双皮奶"
            }
          ]
        },
        //筛选结果列表
        moreScreeningKeywordList: [{
            key: "修改日期",
            value: "2018/12/10中药"
          },
          {
            key: "药品类型",
            value: "中药中药中药中药"
          }
        ],
        moreScreeningKeyword: false, //（筛选关键字下拉框）开关
        iconDownSwitch: false, //（筛选关键字下拉按钮）开关
        tableList: [],
        cheackAllChecked: false,
        checkArr: [],
        checkCompleteArr: [],
        businessType: [],
        currentPage4: 1,
        showSystemPopup: false,
        showScreeningPopup: false,
        systemPopupTitle: "",
        showAddStockPopup: false, //（新增进货弹窗）开关
        showMgmtTheProvincePopup: false, //管理该省
        showCodingProductDetailPopup: false, //（查询结果弹窗）开关
        showShangXiajiaPopup: false, //下架弹窗
        showPatchExport: false, //（导出弹窗）开关
        showExportOkPopup: false, //（导出成功弹窗）开关
        // shelfLifeValue: "", //保质期
        shelfLifeOptions: [{
            //保质期
            value: 6,
            label: 6
          },
          {
            value: 12,
            label: 12
          },
          {
            value: 24,
            label: 24
          },
          {
            value: 36,
            label: 36
          },
        ],
        //informationRateValue: "", //信息费比例
        informationRateOptions: [{
            //信息费比例
            value: "选项1",
            label: "1"
          },
          {
            value: "选项2",
            label: "2"
          },
          {
            value: "选项3",
            label: "3"
          },
          {
            value: "选项4",
            label: "4"
          },
          {
            value: "选项5",
            label: "5"
          }
        ],
        dataValue: "", //生产日期
        org_pur_price_list: [
          //定价范围
          {
            price: "",
            min_num: "",
            max_num: ""
          }
        ],
        codingValue: "152463845958607", //条形码
        showLoadingGif: true,
        totalNumOfArticle: 0, //总条数
        showPageNum: 1, //要展示的页展示的页码
        medical: "", //搜索结果
        org_info_fee_rate:"",
        provinceValue: "", //选中的省份
        province_list_option: [], //省份选项
        checkedCitys: [], //选中的城市
        city_list_option: [], //城市选项
        shang_xiajiaValue: { //上下架弹窗的展现性数据
          id: "",
          coding: "",
          name: "",
          brand_name: "",
          info_fee_rate: "",
          stock: "",
          manu_date: "",
          shelf_life: ""
        },
        bakValue: "",
        bakoption: [{
          value: '选项1',
          label: '黄金糕'
        }, {
          value: '选项2',
          label: '双皮奶'
        }],
        checkProvince_id: "", //选中省份的id
        originalProvinceIndex: "", //选中省份的index
        isMgmtProvince: false, //true是管理该省，false是添加销售范围
        checkProvince_name: "",
        addCityValue: [], //选中城市的数组
        isEdit: false, //判断当前是编辑
        isQuanGuo: false, //点击新增销售范围中的确定 如果是全国的话就是true
      };
    },
    activated() {
      //判断有没有筛选的关键词，有的话就显示下拉框
      if (this.moreScreeningKeywordList.length > 0) {
        this.iconDownSwitch = true;
      }
      this.getList();
    },
    //把秒转成年月日
    methods: {
      changeG(value) {
        var time = new Date(value * 1000);
        var month = (time.getMonth() + 1) > 9 ? time.getMonth() + 1 : '0' + (time.getMonth() + 1);
        var data = time.getDate() > 9 ? time.getDate() : '0' + (time.getDate());
        var hour = time.getHours() > 9 ? time.getHours() : '0' + (time.getHours());
        var minutes = time.getMinutes() > 9 ? time.getMinutes() : '0' + (time.getMinutes());
        var second = time.getSeconds() > 9 ? time.getSeconds() : '0' + (time.getSeconds());
        var times = time.getFullYear() + "-" + month + "-" + data
        return times;
      },
      //获取药品列表
      getList() {
        let _this = this;
        let ourls =
          this.urls +
          "/who/user/refreshToken/" +
          localStorage.getItem("uid") +
          "/" +
          localStorage.getItem("token");
        checkTime(
          new Date().getTime() / 1000,
          ourls,
          localStorage.getItem("reToken")
        );
        _this
          .$http({
            url: this.urls +
              "/who/medical/getList/" +
              localStorage.getItem("uid") +
              "/" +
              localStorage.getItem("token") +
              "/?page=" +
              this.showPageNum,
            method: "get"
          })
          .then(function(res) {
            let data = res.data;
            if (data.code == 1) {
              _this.tableList = data.data.medical_list;
              for (var i in _this.tableList) {
                _this.tableList[i].pur_time = _this.changeG(_this.tableList[i].pur_time); //把毫秒转成年月日
                if(_this.tableList[i].pur_price != null){
                  if(_this.tableList[i].pur_price.indexOf("、") != -1){
                       _this.tableList[i].pur_price = _this.tableList[i].pur_price.replace(/、/g, "\r");
                       //123456
                  }
                }
              }
              _this.totalNumOfArticle = data.data.total;
              _this.showLoadingGif = false;
              localStorage.setItem("nowTimes", new Date().getTime() / 1000); //检查token失效函数
            } else {
              _this.messageAlert(data.msg);
              invalid(data.msg); //检查token失效函数
            }
          })
          .catch(function(error) {
            console.log(error);
          });
      },
      //错误弹窗
      messageAlert(msg) {
        this.$message.error(msg);
      },
      //成功弹窗
      successfulAlert(msg) {
        this.$message({
          message: msg,
          type: 'success'
        });
      },
      //提示框
      infoAlert(msg) {
        this.$message(msg);
      },
      //点击查询结果
      clickCodingResults() {
        var _this = this;
        var sedValue = "coding";
        if (this.isEdit) {
          sedValue = "medical_id";
        }
        if (this.codingValue == "") {
          _this.messageAlert("请输入药品编码");
        }
        let ourls =
          this.urls +
          "/who/user/refreshToken/" +
          localStorage.getItem("uid") +
          "/" +
          localStorage.getItem("token");
        checkTime(
          new Date().getTime() / 1000,
          ourls,
          localStorage.getItem("reToken")
        );
        // 请求开始
        _this
          .$http({
            url: this.urls +
              "/who/medical/getMedicalDetail/" +
              localStorage.getItem("uid") +
              "/" +
              localStorage.getItem("token") + "?" + sedValue + "=" + this.codingValue,
            method: "get",
          })
          .then(function(res) {
            let data = res.data;
            if (data.code == 1) {
              _this.medical = data.data.medical;
              if(_this.medical.info_fee_rate != undefined){
              _this.org_info_fee_rate = _this.medical.info_fee_rate * 100 + '%';
              }
              _this.showCodingProductDetailPopup = true;
              localStorage.setItem("nowTimes", new Date().getTime() / 1000); //检查token失效函数
            } else {
              _this.messageAlert(data.msg);
              invalid(data.msg); //检查token失效函数
            }
          })
          .catch(function(error) {
            console.log(error);
          });
      },
      //获取省份
      getProvinceList() {
        var _this = this;
        let ourls =
          this.urls +
          "/who/user/refreshToken/" +
          localStorage.getItem("uid") +
          "/" +
          localStorage.getItem("token");
        checkTime(
          new Date().getTime() / 1000,
          ourls,
          localStorage.getItem("reToken")
        );
        // 请求开始
        _this
          .$http({
            url: this.urls +
              "/who/medical/getProvinceList/" +
              localStorage.getItem("uid") +
              "/" +
              localStorage.getItem("token"),
            method: "get"
          })
          .then(function(res) {
            let data = res.data;
            if (data.code == 1) {
              _this.province_list_option = data.data.province_list;
              if (!_this.isMgmtProvince) {
                for (var i in _this.province_list_option) {
                  for (var j in _this.medical.region_list) {
                    if (_this.province_list_option[i].province_id == _this.medical.region_list[j].province_id) {
                      _this.province_list_option.splice(i, 1)
                    }
                  }
                }
                _this.province_list_option = _this.province_list_option;
              }
              localStorage.setItem("nowTimes", new Date().getTime() / 1000); //检查token失效函数
            } else {
              _this.messageAlert(data.msg);
              invalid(data.msg); //检查token失效函数
            }
          })
          .catch(function(error) {
            console.log(error);
          });
      },
      //点击管理该省
      mgmtTheProvince(province_id, index, provincename) {
        this.isMgmtProvince = true; //true是管理该省，false是添加销售范围
        this.checkProvince_name = provincename; //保留该省的名称
        this.originalProvinceIndex = index; //保留该省的index值
        this.getProvinceList(); //获取省份选项
        this.provinceValue = province_id; //打开后默认选中该省
        this.provinceValueChange(province_id); //显示该省城市
        this.checkProvince_id = province_id;
        for (var i in this.medical.region_list[index].city_list) {
          //打开后默认选中该省的城市
          this.checkedCitys.push(
            this.medical.region_list[index].city_list[i].city_id
          );
          this.checkedCitys = Array.from(new Set(this.checkedCitys));
        }
        this.showAddStockPopup = false;
        this.showMgmtTheProvincePopup = true;
        this.systemPopupTitle = "管理销售范围";
      },
      //省份的change事件
      provinceValueChange(province_id) {
        var _this = this;
        this.checkProvince_id = province_id;
        this.checkedCitys = [];
        if (province_id == 0) {
          this.city_list_option = [];
          return;
        }
        let ourls =
          this.urls +
          "/who/user/refreshToken/" +
          localStorage.getItem("uid") +
          "/" +
          localStorage.getItem("token");
        checkTime(
          new Date().getTime() / 1000,
          ourls,
          localStorage.getItem("reToken")
        );
        // 请求开始
        _this
          .$http({
            url: this.urls +
              "/who/medical/getCityList/" +
              localStorage.getItem("uid") +
              "/" +
              localStorage.getItem("token") +
              "&province_id=" +
              province_id,
            method: "get"
          })
          .then(function(res) {
            let data = res.data;
            if (data.code == 1) {
              _this.city_list_option = data.data.city_list;
              localStorage.setItem("nowTimes", new Date().getTime() / 1000); //检查token失效函数
            } else {
              _this.messageAlert(data.msg);
              invalid(data.msg); //检查token失效函数
            }
          })
          .catch(function(error) {
            console.log(error);
          });
      },
      //城市的change事件
      selectCity(index) {
        //增加的
        if (this.isMgmtProvince) {
          if (this.checkedCitys.indexOf(this.city_list_option[index].city_id) == -1) {
            for (var i in this.medical.region_list) {
              if (this.medical.region_list[i].province_id == this.checkProvince_id) {
                for (var j in this.medical.region_list[i].city_list) {
                  if (this.medical.region_list[i].city_list[j].city_id == this.city_list_option[index].city_id) {
                    this.medical.region_list[i].city_list.splice(j, 1);
                    break;
                  }
                }
                break;
              }
            }
          } else {
            for (var i in this.medical.region_list) {
              if (this.medical.region_list[i].province_id == this.checkProvince_id) {
                this.medical.region_list[i].city_list.push(this.city_list_option[index]);
                break;
              }
            }
          }
        } else {
          if (this.checkedCitys.indexOf(this.city_list_option[index].city_id) == -1) {
            for (var j in this.addCityValue) {
              if (this.addCityValue[j].city_id == this.city_list_option[index].city_id) {
                this.addCityValue.splice(j, 1);
                break;
              }
            }
          } else {
            this.addCityValue.push(this.city_list_option[index]);
          }
        }
      },
      //删除该省
      deleteProvince(index) {
        var _this = this;
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _this.medical.region_list.splice(index, 1);
          _this.successfulAlert("删除成功!");
          _this.isQuanGuo = false;
        }).catch(() => {
          _this.infoAlert("已取消删除");
        });
      },
      //新增销售范围
      addProvince() {
        this.provinceValue = [];
        this.city_list_option = [];
        this.checkedCitys = [];
        this.addCityValue = [];
        this.isMgmtProvince = false; //true是管理该省，false是添加销售范围
        this.getProvinceList(); //获取省份选项
        this.showAddStockPopup = false;
        this.showMgmtTheProvincePopup = true;
        this.systemPopupTitle = "新增销售范围";
      },
      //点击修改省份弹窗中的确定
      closeChooseProvince() {
        var _this = this;
        this.cancelChooseProvince();
        if (this.checkProvince_id == 0) {
          this.medical.region_list = [];
          this.isQuanGuo = true;
          this.medical.region_list.push({
            "province_id": 0,
            "province": "全国",
          });
          return;
        }
        if (!this.isMgmtProvince) {
          for (var i in _this.province_list_option) {
            if (_this.province_list_option[i].province_id == _this.checkProvince_id) {
              if (this.medical.region_list != undefined) {
                _this.medical.region_list.push({
                  "province_id": _this.province_list_option[i].province_id,
                  "province": _this.province_list_option[i].province,
                  "city_list": _this.addCityValue
                })
              } else {
                var onewArr = [];
                onewArr.push({
                  "province_id": _this.province_list_option[i].province_id,
                  "province": _this.province_list_option[i].province,
                  "city_list": _this.addCityValue
                })
                var region_list = {
                  "region_list": onewArr
                };
                this.medical = Object.assign(this.medical, region_list);
              }
              break;
            }
          }
        } else {
          if (this.checkedCitys == "") {
            this.medical.region_list.splice(this.originalProvinceIndex, 1);
          }
        }
      },
      //点击新增省份弹窗中的取消
      cancelChooseProvince() {
        this.showAddStockPopup = true;
        this.showMgmtTheProvincePopup = false;
        this.systemPopupTitle = "新增进货";
      },
      editFun(id) {
        this.isEdit = true;
        this.codingValue = id;
        this.clickCodingResults();
        this.showSystemPopup = true;
        this.showAddStockPopup = true;
        this.showCodingProductDetailPopup = true;
      },
      //改成两位小数
      changeTwoDecimal_f(x) {
        var s_x = x.toString();
        var pos_decimal = s_x.indexOf('.');
        if (s_x.length <= pos_decimal + 2) {
          s_x += '0';
        }
        return s_x;
      },
      //点击确定  添加进货
      saveProduct() {
        let _this = this;
        if (this.medical.pur_price_list == "") {
          _this.messageAlert("请添加定价范围");
          return;
        }
        if (this.medical.region_list == "" || this.medical.region_list == undefined) {
          _this.messageAlert("请选择销售范围");
          return;
        }
        //将一位小数变成两位：
        var o_info_fee_rate = _this.org_info_fee_rate;
        if (_this.org_info_fee_rate.indexOf("%") > -1) {
          o_info_fee_rate = _this.org_info_fee_rate.replace("%", "") / 100;
        }
        o_info_fee_rate = this.changeTwoDecimal_f(o_info_fee_rate);
        //更新token
        let ourls =
          this.urls +
          "/who/user/refreshToken/" +
          localStorage.getItem("uid") +
          "/" +
          localStorage.getItem("token");
        checkTime(
          new Date().getTime() / 1000,
          ourls,
          localStorage.getItem("reToken")
        );
        //如果是点击编辑库存
        if (this.isEdit) {
          var data = {
            medical_id: _this.medical.id, //药品id
            stock: _this.medical.stock, //库存
            info_fee_rate: o_info_fee_rate, //信息费比例
            pur_price_list: _this.org_pur_price_list, //批发价数组[{price, min_num, max_num}]
            region_list: _this.medical.region_list, //销售范围
          };
          if (_this.medical.stock == "" || o_info_fee_rate == "") {
            _this.messageAlert("请填写完整货品信息");
            return;
          }
          var data = JSON.stringify(data);
          _this
            .$http({
              url: this.urls +
                "/who/medical/editMedical/" +
                localStorage.getItem("uid") +
                "/" +
                localStorage.getItem("token"),
              method: "post",
              data: {
                data: data
              },
            })
            .then(function(res) {
              let data = res.data;
              if (data.code == 1) {
                _this.hideSystemPopup();
                _this.successfulAlert("修改成功");
                _this.getList();
                localStorage.setItem("nowTimes", new Date().getTime() / 1000); //检查token失效函数
              } else {
                _this.messageAlert(data.msg);
                invalid(data.msg); //检查token失效函数
              }
            })
            .catch(function(error) {
              console.log(error);
            });
        }
        //如果是新增进货
        else {
          var data = {
            pid: _this.medical.pid, //药品id
            stock: _this.medical.stock, //库存
            manu_date: _this.medical.manu_date, //生产日期
            batch_num: _this.medical.batch_num, //生产批号
            shelf_life: _this.medical.shelf_life, //保质期
            info_fee_rate: o_info_fee_rate, //信息费比例
            pur_price_list: _this.org_pur_price_list, //批发价数组[{price, min_num, max_num}]
            region_list: _this.medical.region_list, //销售范围
          };
          if (_this.medical.stock == "" || _this.medical.manu_date == "" || _this.medical.batch_num == "" || _this.medical.shelf_life == "" || o_info_fee_rate == []) {
            _this.messageAlert("请填写完整货品信息");
            return;
          }
          var data = JSON.stringify(data);
          _this
            .$http({
              url: this.urls +
                "/who/medical/addMedical/" +
                localStorage.getItem("uid") +
                "/" +
                localStorage.getItem("token"),
              method: "post",
              data: {
                data: data
              },
            })
            .then(function(res) {
              let data = res.data;
              if (data.code == 1) {
                _this.hideSystemPopup();
                _this.successfulAlert("添加成功");
                _this.getList();
                localStorage.setItem("nowTimes", new Date().getTime() / 1000); //检查token失效函数
              } else {
                _this.messageAlert(data.msg);
                invalid(data.msg); //检查token失效函数
              }
            })
            .catch(function(error) {
              console.log(error);
            });
        }
      },
      //添加定价范围
      clickAddPrice() {
        console.log(this.medical.pur_price_list);
        this.medical.pur_price_list.push({
          price: "",
          min_num: "",
          max_num: ""
        });
      },
      //删除定价范围
      deletePrice(index) {
        if (this.medical.pur_price_list.length <= 1) {
          return;
        }
        this.medical.pur_price_list.splice(index, 1);
      },
      //显示新增进货弹窗
      clickAddStock() {
        this.showSystemPopup = true;
        this.showAddStockPopup = true;
        this.systemPopupTitle = "新增进货";
      },
      //显示批量导出弹窗
      clickPatchExport() {
        this.showSystemPopup = true;
        this.showPatchExport = true;
        this.systemPopupTitle = "批量导出";
      },
      //点击确定导出
      determineTheExport() {
        this.showExportOkPopup = true;
        this.showPatchExport = false;
        this.systemPopupTitle = "导出成功";
      },
      //显示筛选弹窗
      clickScreeningPopup() {
        this.showSystemPopup = true;
        this.showScreeningPopup = true;
        this.systemPopupTitle = "筛选条件";
      },
      hideSystemPopup() {
        //关闭弹窗
        this.showSystemPopup = false;
        this.showScreeningPopup = false;
        this.showPatchExport = false;
        this.showExportOkPopup = false;
        this.showAddStockPopup = false;
        this.showCodingProductDetailPopup = false;
        this.systemPopupTitle = "";
        this.medical = "";
        this.isEdit = false;
        this.codingValue = "";
        this.isQuanGuo = false;
        for (var i in this.shang_xiajiaValue) {
          this.shang_xiajiaValue[i] = "";
        }
      },
      //点击删除单个筛选关键词
      deleteScreeningKeywordItem(index) {
        this.moreScreeningKeywordList.splice(index, 1);
        if (this.moreScreeningKeywordList.length == 0) {
          this.moreScreeningKeyword = false;
          this.iconDownSwitch = false;
        }
      },
      //点击清空筛选条件
      clearScreeningConditions() {
        this.$confirm("此操作将删除所有筛选记录?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.moreScreeningKeywordList = [];
            this.moreScreeningKeyword = false;
            this.iconDownSwitch = false;
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      },
      //点击下架
      clickChangeStatus(id, coding, name, brand_name, info_fee_rate, stock, manu_date, shelf_life) {
        this.shang_xiajiaValue.id = id;
        this.shang_xiajiaValue.coding = coding;
        this.shang_xiajiaValue.name = name;
        this.shang_xiajiaValue.brand_name = brand_name;
        this.shang_xiajiaValue.info_fee_rate = info_fee_rate;
        this.shang_xiajiaValue.stock = stock;
        this.shang_xiajiaValue.manu_date = manu_date;
        this.shang_xiajiaValue.shelf_life = shelf_life;
        this.showSystemPopup = true;
        this.systemPopupTitle = "确定下架药品";
        this.showShangXiajiaPopup = true;
      },
      // 确定下架
      changeStatus(status) {
        var _this = this;
        let ourls =
          this.urls +
          "/who/user/refreshToken/" +
          localStorage.getItem("uid") +
          "/" +
          localStorage.getItem("token");
        checkTime(
          new Date().getTime() / 1000,
          ourls,
          localStorage.getItem("reToken")
        );
        _this
          .$http({
            url: this.urls +
              "/who/medical/changeStatus/" +
              localStorage.getItem("uid") +
              "/" +
              localStorage.getItem("token"),
            data: {
              status: status,
              medical_id: _this.shang_xiajiaValue.id
            },
            method: "post"
          })
          .then(function(res) {
            let data = res.data;
            if (data.code == 1) {
              _this.hideSystemPopup();
              _this.getList();
              localStorage.setItem("nowTimes", new Date().getTime() / 1000); //检查token失效函数
            } else {
              _this.messageAlert(data.msg);
              invalid(data.msg); //检查token失效函数
            }
          })
          .catch(function(error) {
            console.log(error);
          });
      },
      //推荐或取消推荐
      is_recommendFun(status, id, index) {
        var oktext = "";
        if (status == 0) {
          status = 1;
          oktext = "推荐成功"
        } else if (status == 1) {
          status = 0;
          oktext = "取消推荐成功"
        }
        var _this = this;
        let ourls =
          this.urls +
          "/who/user/refreshToken/" +
          localStorage.getItem("uid") +
          "/" +
          localStorage.getItem("token");
        checkTime(
          new Date().getTime() / 1000,
          ourls,
          localStorage.getItem("reToken")
        );
        _this
          .$http({
            url: this.urls +
              "/who/medical/changeRecommend/" +
              localStorage.getItem("uid") +
              "/" +
              localStorage.getItem("token"),
            data: {
              is_recommend: status,
              medical_id: id
            },
            method: "post"
          })
          .then(function(res) {
            let data = res.data;
            if (data.code == 1) {
              _this.tableList[index].is_recommend = status;
              _this.successfulAlert(oktext);
              localStorage.setItem("nowTimes", new Date().getTime() / 1000); //检查token失效函数
            } else {
              _this.messageAlert(data.msg);
              invalid(data.msg); //检查token失效函数
            }
          })
          .catch(function(error) {
            console.log(error);
          });
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        this.showPageNum = val;
        this.getList();
      },
      addPath(n1, n2) {
        //点击切换home-bar
        var obj = {};
        obj.n1 = n1;
        obj.n2 = n2;
        this.$store.commit("addPath", obj);
      }
    },
    filters: {
      medType(value) {
        let data;
        if (value == 1) {
          data = 'RX'
        } else if (value == 2) {
          data = "甲类OTC"
        } else {
          data = "乙类OTC"
        }
        return data;
      }
    }
  };
</script>

<style lang="less">
  @import "../css/drugList.less";
</style>
